package UDP.file;
//接收文件

import java.io.File;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 1.创建套接字，并给定端口
 * 2.创建空包接收数据
 * 3.创建管道流存放数据
 * 4.保存
 */
public class file_receive extends Thread {
    private DatagramSocket socket = null;
    private DatagramPacket packet = null;
    private FileOutputStream file = null;
    private int post;

    /**
     * 通过构造方法传入端口
     *
     * @param post
     */
    public file_receive(int post) {
        this.post = post;
    }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket(post);//设置端口号
            file = new FileOutputStream(new File("1.jpg"));//文件管道流
            byte[] wj = new byte[8];
            while (true) {
                packet = new DatagramPacket(wj, 0, wj.length);//创建空包
                socket.receive(packet);//阻塞接收包并存入空包中
                String s = new String(packet.getData(), 0, packet.getLength());//获取包中的内容
                if (s.matches(".*发送.*")) {
                    socket.close();//关闭套接字资源
                    break;
                } else {
                    file.write(packet.getData());
                }
            }
            System.out.println("文件接收完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
